package cn.com.anypay.manager.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * HTTP 工具类
 * 基于 RestTemplate 的 HTTP 请求工具
 */
public final class HttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    private static final RestTemplate REST_TEMPLATE = new RestTemplate();

    // 防止实例化
    private HttpUtils() {}

    /**
     * GET 请求
     */
    public static String get(String url) {
        return get(url, null, String.class);
    }

    /**
     * GET 请求（带参数）
     */
    public static String get(String url, Map<String, String> params) {
        return get(url, params, String.class);
    }

    /**
     * GET 请求（泛型）
     */
    public static <T> T get(String url, Map<String, String> params, Class<T> responseType) {
        try {
            // 构建URL参数
            if (params != null && !params.isEmpty()) {
                StringBuilder urlBuilder = new StringBuilder(url);
                urlBuilder.append(url.contains("?") ? "&" : "?");
                params.forEach((key, value) ->
                    urlBuilder.append(key).append("=").append(value).append("&"));
                url = urlBuilder.substring(0, urlBuilder.length() - 1);
            }

            logger.info("HTTP GET 请求: {}", url);
            ResponseEntity<T> response = REST_TEMPLATE.getForEntity(url, responseType);
            logger.info("HTTP GET 响应状态: {}", response.getStatusCode());

            return response.getBody();
        } catch (Exception e) {
            logger.error("HTTP GET 请求失败: {}", e.getMessage(), e);
            throw new RuntimeException("HTTP GET 请求失败", e);
        }
    }

    /**
     * POST 请求
     */
    public static String post(String url, Object requestBody) {
        return post(url, requestBody, null, String.class);
    }

    /**
     * POST 请求（带请求头）
     */
    public static String post(String url, Object requestBody, Map<String, String> headers) {
        return post(url, requestBody, headers, String.class);
    }

    /**
     * POST 请求（泛型）
     */
    public static <T> T post(String url, Object requestBody, Map<String, String> headers, Class<T> responseType) {
        try {
            logger.info("HTTP POST 请求: {}", url);
            logger.info("HTTP POST 请求体: {}", AnyJsonUtils.toJsonString(requestBody));

            // 设置请求头
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            if (headers != null) {
                headers.forEach(httpHeaders::set);
            }

            HttpEntity<Object> entity = new HttpEntity<>(requestBody, httpHeaders);
            ResponseEntity<T> response = REST_TEMPLATE.postForEntity(url, entity, responseType);

            logger.info("HTTP POST 响应状态: {}", response.getStatusCode());
            return response.getBody();
        } catch (Exception e) {
            logger.error("HTTP POST 请求失败: {}", e.getMessage(), e);
            throw new RuntimeException("HTTP POST 请求失败", e);
        }
    }

    /**
     * PUT 请求
     */
    public static <T> T put(String url, Object requestBody, Class<T> responseType) {
        return put(url, requestBody, null, responseType);
    }

    /**
     * PUT 请求（带请求头）
     */
    public static <T> T put(String url, Object requestBody, Map<String, String> headers, Class<T> responseType) {
        try {
            logger.info("HTTP PUT 请求: {}", url);
            logger.info("HTTP PUT 请求体: {}", AnyJsonUtils.toJsonString(requestBody));

            // 设置请求头
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            if (headers != null) {
                headers.forEach(httpHeaders::set);
            }

            HttpEntity<Object> entity = new HttpEntity<>(requestBody, httpHeaders);
            ResponseEntity<T> response = REST_TEMPLATE.exchange(url, HttpMethod.PUT, entity, responseType);

            logger.info("HTTP PUT 响应状态: {}", response.getStatusCode());
            return response.getBody();
        } catch (Exception e) {
            logger.error("HTTP PUT 请求失败: {}", e.getMessage(), e);
            throw new RuntimeException("HTTP PUT 请求失败", e);
        }
    }

    /**
     * DELETE 请求
     */
    public static <T> T delete(String url, Class<T> responseType) {
        return delete(url, null, responseType);
    }

    /**
     * DELETE 请求（带请求头）
     */
    public static <T> T delete(String url, Map<String, String> headers, Class<T> responseType) {
        try {
            logger.info("HTTP DELETE 请求: {}", url);

            // 设置请求头
            HttpHeaders httpHeaders = new HttpHeaders();
            if (headers != null) {
                headers.forEach(httpHeaders::set);
            }

            HttpEntity<Object> entity = new HttpEntity<>(httpHeaders);
            ResponseEntity<T> response = REST_TEMPLATE.exchange(url, HttpMethod.DELETE, entity, responseType);

            logger.info("HTTP DELETE 响应状态: {}", response.getStatusCode());
            return response.getBody();
        } catch (Exception e) {
            logger.error("HTTP DELETE 请求失败: {}", e.getMessage(), e);
            throw new RuntimeException("HTTP DELETE 请求失败", e);
        }
    }

    /**
     * 表单提交
     */
    public static String postForm(String url, Map<String, String> formData) {
        try {
            logger.info("HTTP POST FORM 请求: {}", url);
            logger.info("HTTP POST FORM 数据: {}", formData);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            // 构建表单数据
            StringBuilder formBody = new StringBuilder();
            if (formData != null) {
                formData.forEach((key, value) ->
                    formBody.append(key).append("=").append(value).append("&"));
                if (formBody.length() > 0) {
                    formBody.setLength(formBody.length() - 1); // 移除最后的&
                }
            }

            HttpEntity<String> entity = new HttpEntity<>(formBody.toString(), headers);
            ResponseEntity<String> response = REST_TEMPLATE.postForEntity(url, entity, String.class);

            logger.info("HTTP POST FORM 响应状态: {}", response.getStatusCode());
            return response.getBody();
        } catch (Exception e) {
            logger.error("HTTP POST FORM 请求失败: {}", e.getMessage(), e);
            throw new RuntimeException("HTTP POST FORM 请求失败", e);
        }
    }

    /**
     * 获取 RestTemplate 实例
     */
    public static RestTemplate getRestTemplate() {
        return REST_TEMPLATE;
    }
}